package com.zyk.scaffold.core.component;

import lombok.extern.slf4j.Slf4j;
import org.springframework.core.io.ClassPathResource;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.script.DefaultRedisScript;
import org.springframework.scripting.support.ResourceScriptSource;

import java.util.ArrayList;
import java.util.List;

/**
 * redis 滑动限流组件（最后一次成功开始酸有效期）
 */
@Slf4j
public class RedisSlideLimitComponent {

    private static final String REDIS_LIMIT_KEY = "limit:slide:";

    private StringRedisTemplate stringRedisTemplate;


    private DefaultRedisScript<Long> redisScript = new DefaultRedisScript<>();

    {

        redisScript.setScriptSource(new ResourceScriptSource(
                new ClassPathResource("META-INF/scripts/slide-time-limiter.lua")));
        redisScript.setResultType(Long.class);
    }

    public RedisSlideLimitComponent(StringRedisTemplate stringRedisTemplate) {
        this.stringRedisTemplate = stringRedisTemplate;
    }

    /**
     * 尝试获取key令牌，true 获取成功、false 获取失败
     * @param key 识别key
     * @param limitCount 数量
     * @param seconds 滑动投放时间
     * @return
     */
    public boolean tryAccess(String key, int limitCount, int seconds) {
        List<String> keys = new ArrayList<>();
        keys.add(REDIS_LIMIT_KEY + key);
        Long count = stringRedisTemplate.execute(redisScript, keys, String.valueOf(limitCount), String.valueOf(seconds));
        if (count != 0) {
            return true;
        } else {
            return false;
        }
    }

    public boolean release(String key) {
        stringRedisTemplate.opsForValue().set(REDIS_LIMIT_KEY + key, "0");
        return true;
    }
}
